/**
 * @placeholder 提示
 * @title 悬停文字
 * @showClearButton
 * @readonly
 * @Visiable
 * @dispDefaultLang
 * @required
 * @requiredMessage
 * @requiredMultRule
 * @maxLength
 * @maxlengthMessage
 * @regexp
 * @regexpmessage
 */

export class MultilingualComponent {
	constructor(target, options) {
		this.element = target;
		if (typeof target == "string") {
			this.element = document.querySelector(target);
		}
		this.element.style.position = "relative";
		this.element.style.width = '100%';
		if (!this.element) {
			return console.error("实例子不存在");
		}

		this.watchList = {};
		this.handelData = {};
		this.init(options);
		console.log(options)
		return this;
	}
	watch(name, callBack) {
		this.watchList[name] = callBack ? callBack : () => {};
		return this;
	}
	init(options) {
		this.options = options;
		this.dataChange = options.dataChange;
		this.ChangeLang = options.changeLang||options.ChangeLang;
		this.languageInfo = options.languageInfo;

		this.placeholder = options.placeholder && options.placeholder != "undefined" ? options.placeholder : "";
		this.title = options.showHint?(options.hintMode=="placeholder"?this.placeholder:options.hintMsg):'';
		this.showClearButton = options.showClearButton;
		this.isTextArea = options.isTextArea;
		this.resize = options.resize;
		this.heightAuto = options.heightAuto
		this.rows = options.rows
		this.element.style.direction = this.direction = this.options.direction || 'ltr'
		this.containList = options.containList;
		this.render();
		if (options.readonly) {
			this.setReadOnly(true)
		}

		return this;
	}
	render() {
		let css = `
		<style >
		.MultilingualContent{
			margin: 0 1px 0 1px !important;
			padding:0;
			// border: 1px solid #ddd;
			border-radius: 2px;
			display: block;
			font-size: 14px;

			display:flex;
			overflow:hidden;
			border-radius:4px;
			background: #fff;
			user-select: none;
			width:100%;
			height:30px;
			line-height:30px;

		}
		.Teld_Multilingual_Focus,.MultilingualContent:not(.isReadonly):hover{
			//border-color:var(--color-hover) !important;
		}
		.MultilingualContent.isReadonly .MultilingualText{
			// background:rgba(59, 59, 59, 0)
		}

		.MultilingualContent .LanguageType {
			${this.direction!='RTL'?'border-right: 1px solid #ddd;':'border-left: 1px solid #ddd;'}
			border-radius: 2px;
			padding: 0px 10px;
			display: flex;
			justify-content: center;
			width:40px;
			align-items: center;
        	background: #fff;
			margin: 6px;
			height:18px;
			color: #4E5969;

		}

		.MultilingualContent .LanguageType span{
			display:inline-block;
		 	overflow:hidden;
		  white-space: nowrap;
		  text-overflow: ellipsis;
		  -o-text-overflow:ellipsis;
		}
		.MultilingualContent .MultilingualText{
			flex:1;
			padding:0;
			border: 0;outline: 0;
			diaplay:inline-block;
			height:100%;
			width:100%;
			font-size:14px;
			padding-left:2px;
			color:rgba(0, 0, 0, var(--t-color-opacity, /*批量处理90%透明度*/.9));
			cursor: pointer;
			line-height:20px;

		}
		.MultilingualContent .MultilingualText.heightAuto{
			overflow:hidden;
		}
		.MultilingualContent .MultilingualText.padding_10{

			${this.direction=='RTL'?'padding-right:8px':'padding-left:0px'}

		}
		.MultilingualContent .MultilingualText.padding_2{
			${this.direction=='RTL'?'padding-right:2px':'padding-left:2px'}

		}

		.MultilingualContent .MultilingualText::placeholder{
			color:rgba(0, 0, 0, .32);
			font-size:14px;
		}
		.MultilingualContent .MultilingualText_Resize{
			resize:vertical
		}
		.MultilingualContent .MultilingualText_NotResize{
			resize:none
		}
		.MultilingualContent .MultilingualText.MultilingualTextTextArea{
			min-height:32px;
			padding-top:6px;
		}
		.MultilingualContent .MultilingualText.MultilingualTextInput{

			height: 32px;
		}
		.translateAll{
			color: #1664FF;
			font-family: PingFang SC;
			font-size: 12px;
			font-style: normal;
			font-weight: 400;
			line-height: normal;
			position: absolute;
			right: 0;
			top: -24px;
			cursor: pointer;
		}
		.MultilingualErrorMessage{
			color: #ff5a66;
			font-size: 14px;
			font-style: normal;
			font-weight: 400;
			line-height: 14px; /* 100% */
			display: inline-block;
			margin-top:-11px;
		}
		</style>
		`;
		// <span class='translateAll' style="display:none">一键翻译</span>
		let html = `

		`;
		if (this.containList) {
			html = {}
    }
		let inputComponent = `
		<input tabindex='0' title="${this.title}"  class='MultilingualTextInput PADDINGTEMPLATE MultilingualText MultilingualText_{item.langSuffix}' data-type="{item.langSuffix}" placeholder="${this.placeholder}"/>
		`;
		if (!this.isTextArea) {
			inputComponent = `
			<textarea rows="${this.rows ? this.rows : 3}"  title="${this.title}" class='${this.resize?'MultilingualText_Resize':'MultilingualText_NotResize'} ${this.heightAuto?'heightAuto':''} MultilingualText MultilingualText_{item.langSuffix} PADDINGTEMPLATE MultilingualTextTextArea' data-type="{item.langSuffix}" placeholder="${this.placeholder}"></textarea>
			`;
		}
		this.languageInfo.forEach((item, index) => {
			this.handelData[item.langSuffix] = "";
			let _inputComponent = `${inputComponent.replace(/{item.langSuffix}/gi, item.langSuffix).replace(/\${Lang}/gi, item.DisplayName ? item.DisplayName : "").replace(/PADDINGTEMPLATE/ig,(index == 0?"padding_10":"padding_2"))}`
			console.log(_inputComponent)
			if (this.containList) {
				html[item.langSuffix] = `
			<p class='MultilingualContent' style="${!this.isTextArea ? 'height:auto;' : ''} ${index != this.languageInfo.length - 1 ? 'margin-bottom:' + (this.options.space ? this.options.space + 'px' : '12px') : ''}" class='MultilingualErrorMessage MultilingualErrorMessage_${item.langSuffix}'>
				<span class='LanguageType' title="${item.ShortName}" >
					<span>${item.ShortName}</span>
				</span>
				${_inputComponent}
			</p>
			`;
			} else {
				html += `
			<p class='MultilingualContent' style="${!this.isTextArea?'height:auto;':''} ${index != this.languageInfo.length - 1 ? 'margin-bottom:' + (this.options.space ? this.options.space + 'px' : '12px') : ''}" class='MultilingualErrorMessage MultilingualErrorMessage_${item.langSuffix}'>
				<span class='LanguageType' title="${item.ShortName}">
					<span>${item.ShortName}</span>
				</span>
				${_inputComponent}
			</p>
			<span style="display:none;${index != this.languageInfo.length - 1 ? 'margin-bottom:' + (this.options.space ? this.options.space + 'px' : '12px') : ''}" class='MultilingualErrorMessage MultilingualErrorMessage_${item.langSuffix}'></span>
			`;
			}

		});
		if (this.containList) {
			for (let i in html) {
				let target = null
				for (let jj = 0; jj < this.containList.length; jj++){
					if (this.containList[jj].classList.contains(`MultilingualText_${i}`)) {
            target = this.containList[jj];
          }
				}

				if (target) {
					target.innerHTML = html[i]
				}
			}
			this.element.innerHTML = css;
		} else {
			this.element.innerHTML = css + html;
		}

		this.regestorEvent();
		this.setReadOnly(this.options.readonly)
		return this;
	}
	setReadOnly(val) {
		this.readonly = val
		// if (val) {
		// 	this.element.querySelector(".translateAll").style.display = "none";
		// } else {
		// 	this.element.querySelector(".translateAll").style.display = "block";
		// }
		// 注册点击，获取焦点，失去焦点事件
		let inputList = this.element.querySelectorAll(".MultilingualText");
if (this.containList) {
  inputList = [];
  this.containList.forEach(element => {
    inputList.push(element.querySelector('.MultilingualText'));
  });
}
		inputList.forEach((item) => {
			if (val) {
				item.setAttribute("readonly", '');
				item.style.background='rgba(59, 59, 59, 0)'
				item.parentNode.style.background="rgba(0,0,0,.05)"
				item.parentNode.querySelector('.LanguageType').style.background='rgba(59, 59, 59, 0)'
				item.parentNode.classList.add("isReadonly")
			} else {
				item.removeAttribute("readonly");
				item.style.background='#fff'
				item.parentNode.style.background="#fff"
				item.parentNode.querySelector('.LanguageType').style.background='#fff'
				item.parentNode.classList.remove("isReadonly")
				//item.querySelector('.LanguageType').style.background='#fff'
			}
		});
	}
	setValue(langSuffix, val) {
		console.log('=========aaaa========', langSuffix, val)
      if (val != 'undefined' && typeof val != 'undefined') {
        if (this.containList) {
          let target = null;

          for (let jj = 0; jj < this.containList.length; jj++) {
            if (
              this.containList[jj].className.includes(
                `MultilingualText_${langSuffix}`,
              )
            ) {
              target = this.containList[jj];
            }
          }
          if (target) {
            let multilingualTextElement = target.querySelector(
              '.MultilingualText_' + langSuffix,
            );

            if (multilingualTextElement.tagName === 'INPUT') {
              multilingualTextElement.value = val;
            } else {
              multilingualTextElement.innerHTML = val;
            }
          }
        } else {
          let element = this.element.querySelector(
            '.MultilingualText_' + langSuffix,
          );
          if (element && element.tagName === 'INPUT') {
            element.value = val;
          } else {
            element.innerHTML = val;
          }
        }
      }
	}
	setPlaceHolder(val) {
		if (!val) val = "";
		let inputList = this.element.querySelectorAll("input");
		if (this.containList) {
      inputList = [];
      this.containList.forEach(element => {
        inputList.push(element.querySelector('.MultilingualText'));
      });
    }
		inputList.forEach((item) => {
			let element = this.languageInfo.find((element) => {
				return element.langSuffix == this.getDataType(item);
			});
			let placeholder = val.replace(/\${Lang}/gi, element.DisplayName ? element.DisplayName : "");
			item.setAttribute("placeholder", placeholder);
		});
	}
	setValidate(info) {
		let MultilingualErrorMessage = this.element.querySelectorAll(".MultilingualErrorMessage");
		MultilingualErrorMessage.forEach((element) => {
			element.style.display = "none";
		});
		if (info) {
			for (let i in info) {
				let element = this.element.querySelector(".MultilingualErrorMessage_" + i);
				if(element){
					element.innerHTML = info[i].message;
					element.style.display = "block";
				}

			}
		}
	}
	regestorEvent() {
		// 注册点击，获取焦点，失去焦点事件
		let inputList = this.element.querySelectorAll(".MultilingualText");
		if (this.containList) {
			inputList = []
			this.containList.forEach(element => {
				inputList.push(element.querySelector('.MultilingualText'));
			});
		}
		inputList.forEach((item) => {
			let element = this.languageInfo.find((element) => {
				return element.langSuffix == this.getDataType(item);
			});
			if (this.options.defaultValue&&element.IsMain) {
				item.value = this.options.defaultValue;
				this.ChangeLang && this.ChangeLang instanceof Function ? this.ChangeLang(this.getDataType(item)) : "";
				this.dataChange && this.dataChange instanceof Function ? this.dataChange(this.options.defaultValue) : "";
			}

			item.onfocus = () => {
				if(this.readonly) return
				item.parentNode.classList.add("Teld_Multilingual_Focus");
				this.ChangeLang && this.ChangeLang instanceof Function ? this.ChangeLang(this.getDataType(item)) : "";
			};
			item.onblur = () => {
				item.parentNode.classList.remove("Teld_Multilingual_Focus");
			};
			item.onkeyup = () => {
				if (!this.isTextArea&&this.heightAuto) {
					this.adjustTextareaHeight(item);
				}
				if (!item.value || item.value == "undefined") item.value='';
				this.handelData[this.getDataType(item)] = item.value;
				this.dataChange && this.dataChange instanceof Function ? this.dataChange(item.value) : "";
			};
		});
		// this.element.querySelector(".translateAll").onclick = () => {
		// 	alert("执行翻译服务");
		// };
		return this;
	}
	adjustTextareaHeight(textarea) {
		textarea.style.height = "auto";
		textarea.style.height = textarea.scrollHeight + "px";
	}
	getDataType(data) {
		return data.getAttribute("data-type");
	}
}
window.MultilingualComponent = MultilingualComponent;
